
import React from 'react';
import { useParams, Link } from 'react-router-dom';
import { ArrowLeft, Calendar, User, FileText, AlertCircle, BarChart3, MessageSquare, Heart } from 'lucide-react';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion";
import { Button } from "@/components/ui/button";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useInView } from '@/utils/animation';
import { useIsMobile } from '@/hooks/use-mobile';

// Mock data - in a real app, this would come from an API
const reportData = {
  "血常规检查": {
    id: "blood-routine-001",
    title: "血常规检查",
    date: "2023-06-15",
    institution: "鹰朗健康体检中心",
    doctor: "李医生",
    status: "completed",
    abnormal: false,
    categoryIcon: <FileText className="h-5 w-5" />,
    gradient: "linear-gradient(120deg, #4FD1C5 0%, #63B3ED 100%)",
    items: [
      { name: "白细胞计数 (WBC)", value: "6.8", unit: "10^9/L", reference: "4.0-10.0", abnormal: false },
      { name: "红细胞计数 (RBC)", value: "5.2", unit: "10^12/L", reference: "4.0-5.5", abnormal: false },
      { name: "血红蛋白 (HGB)", value: "156", unit: "g/L", reference: "120-160", abnormal: false },
      { name: "血小板计数 (PLT)", value: "245", unit: "10^9/L", reference: "100-300", abnormal: false },
      { name: "中性粒细胞百分比 (NEU%)", value: "60.5", unit: "%", reference: "50-70", abnormal: false },
      { name: "淋巴细胞百分比 (LYM%)", value: "32.4", unit: "%", reference: "20-40", abnormal: false },
    ],
    interpretation: "您的血常规检查结果显示各项指标均在正常范围内，未见明显异常。白细胞、红细胞、血红蛋白及血小板等重要指标均处于参考值范围，说明您目前的造血功能正常，免疫系统功能良好。",
    advice: "建议您继续保持良好的生活习惯，定期体检，均衡饮食，适当运动，保持充足的睡眠。由于血常规指标可以反映身体的整体健康状况，建议您每年进行一次常规体检。"
  },
  "肝功能检查": {
    id: "liver-function-001",
    title: "肝功能检查",
    date: "2023-05-30",
    institution: "鹰朗健康体检中心",
    doctor: "张医生",
    status: "completed",
    abnormal: true,
    categoryIcon: <FileText className="h-5 w-5" />,
    gradient: "linear-gradient(120deg, #F87171 0%, #FCA5A5 100%)",
    items: [
      { name: "丙氨酸氨基转移酶 (ALT)", value: "68", unit: "U/L", reference: "5-40", abnormal: true },
      { name: "天门冬氨酸氨基转移酶 (AST)", value: "42", unit: "U/L", reference: "8-40", abnormal: true },
      { name: "γ-谷氨酰转移酶 (GGT)", value: "35", unit: "U/L", reference: "11-50", abnormal: false },
      { name: "碱性磷酸酶 (ALP)", value: "87", unit: "U/L", reference: "40-150", abnormal: false },
      { name: "总胆红素 (TBIL)", value: "12.5", unit: "μmol/L", reference: "5.1-17.0", abnormal: false },
      { name: "白蛋白 (ALB)", value: "45", unit: "g/L", reference: "40-55", abnormal: false },
    ],
    interpretation: "您的肝功能检查结果显示丙氨酸氨基转移酶(ALT)和天门冬氨酸氨基转移酶(AST)轻度升高，这可能表明肝脏存在轻微的炎症反应或损伤。其他肝功能指标如γ-谷氨酰转移酶、碱性磷酸酶、总胆红素和白蛋白均在正常范围内。",
    advice: "建议您注意饮食调理，减少高脂肪、高糖分食物摄入，避免饮酒和熬夜。增加新鲜蔬果摄入，适当运动有助于改善肝功能。建议3个月后复查肝功能。如果出现疲劳、食欲不振、黄疸等症状，请及时就医。"
  },
  "心电图检查": {
    id: "ecg-001",
    title: "心电图检查",
    date: "2023-04-22",
    institution: "鹰朗健康体检中心",
    doctor: "王医生",
    status: "completed",
    abnormal: false,
    categoryIcon: <FileText className="h-5 w-5" />,
    gradient: "linear-gradient(120deg, #A78BFA 0%, #C4B5FD 100%)",
    items: [
      { name: "心率", value: "72", unit: "次/分", reference: "60-100", abnormal: false },
      { name: "PR间期", value: "160", unit: "ms", reference: "120-200", abnormal: false },
      { name: "QRS时限", value: "90", unit: "ms", reference: "60-110", abnormal: false },
      { name: "QT间期", value: "380", unit: "ms", reference: "350-440", abnormal: false },
      { name: "节律", value: "窦性心律", unit: "", reference: "窦性心律", abnormal: false },
    ],
    interpretation: "您的心电图检查结果显示窦性心律，心率为72次/分，各项指标均在正常范围内。PR间期、QRS时限以及QT间期均未见异常，表明您的心脏电传导系统功能正常。",
    advice: "目前您的心脏功能良好，建议继续保持健康的生活方式，适当控制体重，定期锻炼，控制血压，避免过度劳累和情绪波动。建议每年进行一次心电图检查，以监测心脏健康状况。"
  },
  "尿常规检查": {
    id: "urine-routine-001",
    title: "尿常规检查",
    date: "2023-03-10",
    institution: "鹰朗健康体检中心",
    doctor: "刘医生",
    status: "completed",
    abnormal: false,
    categoryIcon: <FileText className="h-5 w-5" />,
    gradient: "linear-gradient(120deg, #FBBF24 0%, #FCD34D 100%)",
    items: [
      { name: "尿蛋白", value: "阴性", unit: "", reference: "阴性", abnormal: false },
      { name: "尿糖", value: "阴性", unit: "", reference: "阴性", abnormal: false },
      { name: "尿潜血", value: "阴性", unit: "", reference: "阴性", abnormal: false },
      { name: "尿白细胞", value: "阴性", unit: "", reference: "阴性", abnormal: false },
      { name: "尿比重", value: "1.020", unit: "", reference: "1.010-1.025", abnormal: false },
      { name: "pH值", value: "6.0", unit: "", reference: "4.5-8.0", abnormal: false },
    ],
    interpretation: "您的尿常规检查结果显示各项指标均正常。尿蛋白、尿糖、尿潜血和尿白细胞均为阴性，尿比重和pH值均在正常范围内，表明您的泌尿系统功能良好。",
    advice: "您的尿常规检查结果正常，建议您保持良好的生活习惯，多饮水，注意个人卫生，避免憋尿，适量运动，合理饮食。建议每年进行一次尿常规检查，以监测泌尿系统健康状况。"
  }
};

const ReportDetail = () => {
  const { id } = useParams();
  const isMobile = useIsMobile();
  const { ref: headerRef, isInView: headerIsVisible } = useInView();
  const { ref: contentRef, isInView: contentIsVisible } = useInView(0.1);
  
  // Find the report data based on ID
  // In a real app, this would be an API call
  const reportTitle = id?.replace(/-/g, ' ');
  const report = reportData[reportTitle as keyof typeof reportData];
  
  if (!report) {
    return (
      <div className="min-h-screen pt-20 px-6 md:px-10 pb-10 flex items-center justify-center">
        <Card className="w-full max-w-lg">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <AlertCircle className="h-5 w-5 text-destructive" />
              报告未找到
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-foreground/70">
              抱歉，未能找到ID为 {id} 的报告数据。请返回报告列表重新选择。
            </p>
          </CardContent>
          <CardFooter>
            <Button variant="outline" asChild>
              <Link to="/report-analysis">
                <ArrowLeft className="mr-2 h-4 w-4" />
                返回报告列表
              </Link>
            </Button>
          </CardFooter>
        </Card>
      </div>
    );
  }

  const abnormalItems = report.items.filter(item => item.abnormal);
  const hasAbnormalItems = abnormalItems.length > 0;

  return (
    <div className={`min-h-screen ${isMobile ? 'pt-16 pb-20' : 'pt-20'} px-6 md:px-10 pb-10`}>
      <div className="max-w-4xl mx-auto">
        {/* Back button */}
        <div 
          ref={headerRef}
          className={`mb-6 transition-all duration-700 delay-100 ${
            headerIsVisible ? 'opacity-100' : 'opacity-0 translate-y-10'
          }`}
        >
          <Button variant="outline" asChild className="gap-2">
            <Link to="/report-analysis">
              <ArrowLeft className="h-4 w-4" />
              返回
            </Link>
          </Button>
        </div>

        {/* Report header */}
        <div 
          className={`mb-8 transition-all duration-700 delay-200 ${
            headerIsVisible ? 'opacity-100' : 'opacity-0 translate-y-10'
          }`}
        >
          <h1 className="text-3xl font-bold mb-4 flex items-center gap-3">
            <span className="p-2 rounded-full" style={{ background: report.gradient }}>
              {report.categoryIcon}
            </span>
            {report.title}
            {report.abnormal && (
              <span className="text-sm font-medium text-white bg-destructive px-3 py-1 rounded-full">
                异常
              </span>
            )}
          </h1>
          <div className="flex flex-wrap gap-6 text-foreground/70">
            <div className="flex items-center gap-1.5">
              <Calendar className="h-4 w-4" />
              <span>{report.date}</span>
            </div>
            <div className="flex items-center gap-1.5">
              <User className="h-4 w-4" />
              <span>检查医生: {report.doctor}</span>
            </div>
            <div className="flex items-center gap-1.5">
              <FileText className="h-4 w-4" />
              <span>检查机构: {report.institution}</span>
            </div>
          </div>
        </div>

        {/* Main content */}
        <div 
          ref={contentRef}
          className={`transition-all duration-700 delay-300 ${
            contentIsVisible ? 'opacity-100' : 'opacity-0 translate-y-10'
          }`}
        >
          <Tabs defaultValue="overview" className="w-full">
            <TabsList className="grid grid-cols-4 mb-6">
              <TabsTrigger value="overview">概览</TabsTrigger>
              <TabsTrigger value="data">检测数据</TabsTrigger>
              <TabsTrigger value="interpretation">数据解读</TabsTrigger>
              <TabsTrigger value="advice">健康建议</TabsTrigger>
            </TabsList>
            
            {/* Overview Tab */}
            <TabsContent value="overview">
              <div className="grid gap-6">
                {/* Abnormal alert if needed */}
                {hasAbnormalItems && (
                  <Alert variant="destructive" className="mb-6">
                    <AlertCircle className="h-5 w-5" />
                    <AlertTitle>检测到异常指标</AlertTitle>
                    <AlertDescription>
                      您的 {report.title} 检测中有 {abnormalItems.length} 项指标异常，建议关注异常指标并咨询医生。
                    </AlertDescription>
                  </Alert>
                )}
                
                {/* Quick summary cards */}
                <div className="grid sm:grid-cols-3 gap-4">
                  <Card>
                    <CardHeader className="pb-2">
                      <CardTitle className="text-sm font-medium flex items-center gap-2">
                        <BarChart3 className="h-4 w-4 text-primary" />
                        检测项目
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-2xl font-bold">{report.items.length}</p>
                    </CardContent>
                  </Card>
                  
                  <Card>
                    <CardHeader className="pb-2">
                      <CardTitle className="text-sm font-medium flex items-center gap-2">
                        <AlertCircle className="h-4 w-4 text-primary" />
                        异常指标
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-2xl font-bold">{abnormalItems.length}</p>
                    </CardContent>
                  </Card>
                  
                  <Card>
                    <CardHeader className="pb-2">
                      <CardTitle className="text-sm font-medium flex items-center gap-2">
                        <Calendar className="h-4 w-4 text-primary" />
                        检查时间
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-base font-medium">{report.date}</p>
                    </CardContent>
                  </Card>
                </div>
                
                {/* Data preview */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <BarChart3 className="h-5 w-5 text-primary" />
                      主要检测数据
                    </CardTitle>
                    <CardDescription>
                      以下是检测报告中的关键指标数据
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>检测项目</TableHead>
                          <TableHead>结果</TableHead>
                          <TableHead>参考范围</TableHead>
                          <TableHead>状态</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {report.items.slice(0, 3).map((item) => (
                          <TableRow key={item.name}>
                            <TableCell className="font-medium">{item.name}</TableCell>
                            <TableCell>
                              {item.value} {item.unit}
                            </TableCell>
                            <TableCell>{item.reference}</TableCell>
                            <TableCell>
                              {item.abnormal ? (
                                <span className="text-destructive font-medium">异常</span>
                              ) : (
                                <span className="text-green-600 font-medium">正常</span>
                              )}
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </CardContent>
                  <CardFooter>
                    <Button variant="link" size="sm" asChild>
                      <Link to="#data">查看全部数据</Link>
                    </Button>
                  </CardFooter>
                </Card>
                
                {/* Interpretation preview */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <MessageSquare className="h-5 w-5 text-primary" />
                      数据解读
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <p className="text-foreground/80">
                      {report.interpretation.substring(0, 120)}...
                    </p>
                  </CardContent>
                  <CardFooter>
                    <Button variant="link" size="sm" asChild>
                      <Link to="#interpretation">阅读完整解读</Link>
                    </Button>
                  </CardFooter>
                </Card>
              </div>
            </TabsContent>
            
            {/* Data Tab */}
            <TabsContent value="data">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <BarChart3 className="h-5 w-5 text-primary" />
                    全部检测数据
                  </CardTitle>
                  <CardDescription>
                    {report.title} 的全部检测指标结果
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>检测项目</TableHead>
                        <TableHead>结果</TableHead>
                        <TableHead>单位</TableHead>
                        <TableHead>参考范围</TableHead>
                        <TableHead>状态</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {report.items.map((item) => (
                        <TableRow key={item.name}>
                          <TableCell className="font-medium">{item.name}</TableCell>
                          <TableCell>{item.value}</TableCell>
                          <TableCell>{item.unit}</TableCell>
                          <TableCell>{item.reference}</TableCell>
                          <TableCell>
                            {item.abnormal ? (
                              <span className="text-destructive font-medium">异常</span>
                            ) : (
                              <span className="text-green-600 font-medium">正常</span>
                            )}
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </CardContent>
              </Card>
            </TabsContent>
            
            {/* Interpretation Tab */}
            <TabsContent value="interpretation">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <MessageSquare className="h-5 w-5 text-primary" />
                    数据解读
                  </CardTitle>
                  <CardDescription>
                    专业的检测数据分析和解读
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="prose prose-sm max-w-none">
                    <h3>整体评估</h3>
                    <p>{report.interpretation}</p>
                    
                    {hasAbnormalItems && (
                      <>
                        <h3 className="text-destructive">异常指标分析</h3>
                        <ul>
                          {abnormalItems.map((item) => (
                            <li key={item.name}>
                              <strong>{item.name}:</strong> 您的检测结果为 {item.value} {item.unit}，
                              参考范围为 {item.reference}。
                              {item.name.includes('ALT') && (
                                <span> 丙氨酸氨基转移酶轻度升高可能与肝细胞损伤有关，常见于病毒性肝炎、药物性肝损伤、酒精性肝病等。</span>
                              )}
                              {item.name.includes('AST') && (
                                <span> 天门冬氨酸氨基转移酶轻度升高也提示存在肝细胞损伤，但此项指标不仅存在于肝脏中，心脏、肌肉等组织也有分布。</span>
                              )}
                            </li>
                          ))}
                        </ul>
                      </>
                    )}
                  </div>
                </CardContent>
              </Card>
            </TabsContent>
            
            {/* Advice Tab */}
            <TabsContent value="advice">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Heart className="h-5 w-5 text-primary" />
                    健康建议
                  </CardTitle>
                  <CardDescription>
                    基于您的检测结果，为您提供健康管理建议
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="prose prose-sm max-w-none">
                    <h3>专业建议</h3>
                    <p>{report.advice}</p>
                    
                    <h3>生活方式建议</h3>
                    <Accordion type="single" collapsible className="w-full">
                      <AccordionItem value="diet">
                        <AccordionTrigger>饮食建议</AccordionTrigger>
                        <AccordionContent>
                          {report.abnormal ? (
                            <ul>
                              <li>减少高脂肪、高糖、高盐食物摄入</li>
                              <li>增加新鲜蔬菜水果摄入</li>
                              <li>优先选择全谷物食品</li>
                              <li>保持充分饮水，避免酒精饮料</li>
                              <li>控制总热量摄入，保持健康体重</li>
                            </ul>
                          ) : (
                            <ul>
                              <li>保持均衡饮食，摄入充足蔬果</li>
                              <li>适量摄入优质蛋白质</li>
                              <li>控制盐分和油脂摄入</li>
                              <li>保持良好的饮水习惯</li>
                            </ul>
                          )}
                        </AccordionContent>
                      </AccordionItem>
                      
                      <AccordionItem value="exercise">
                        <AccordionTrigger>运动建议</AccordionTrigger>
                        <AccordionContent>
                          <ul>
                            <li>每周进行至少150分钟中等强度有氧运动</li>
                            <li>每周2-3次力量训练</li>
                            <li>保持日常活动，减少久坐时间</li>
                            <li>根据个人身体状况选择适合的运动方式</li>
                          </ul>
                        </AccordionContent>
                      </AccordionItem>
                      
                      <AccordionItem value="sleep">
                        <AccordionTrigger>睡眠建议</AccordionTrigger>
                        <AccordionContent>
                          <ul>
                            <li>保持规律作息，每晚7-8小时充足睡眠</li>
                            <li>睡前避免使用电子设备</li>
                            <li>保持卧室环境舒适，温度适宜</li>
                            <li>避免咖啡因、酒精等影响睡眠的物质</li>
                          </ul>
                        </AccordionContent>
                      </AccordionItem>
                    </Accordion>
                    
                    <h3>后续建议</h3>
                    {report.abnormal ? (
                      <p>建议3个月内复查相关异常指标，如症状加重请及时就医。定期体检有助于及时发现健康问题，建议每年进行一次全面体检。</p>
                    ) : (
                      <p>您的检查结果良好，建议继续保持健康的生活方式，并每年进行一次常规体检，以便及时了解自己的健康状况。</p>
                    )}
                  </div>
                </CardContent>
              </Card>
            </TabsContent>
          </Tabs>
          
          {/* Disclaimer */}
          <div className="mt-10 text-center text-xs text-foreground/50 max-w-2xl mx-auto">
            <Separator className="mb-4" />
            <p>信息由AI生成，仅做参考，不能作为诊断依据。如有健康问题，请咨询专业医疗人员。</p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ReportDetail;
